﻿/*
 Microsoft Public License (MS-PL)
 --------------------------------
 * * This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.

1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SD.CoreLibrary.CronExpressionDescripter
{
    public class CronExpressionNormalizer
    {
        private string _expression;
        private CronDescriptionOptions _options;

        public CronExpressionNormalizer(string expression, CronDescriptionOptions options)
        {
            _expression = expression;
            _options = options;
        }

        public string[] Parse()
        {
            // Initialize all elements of parsed array to empty strings
            string[] parsed = new string[7].Select(el => "").ToArray();

            if (string.IsNullOrEmpty(_expression))
            {
                throw new MissingFieldException("CronExpressionNormalizer", "expression");
            }
            else
            {
                string[] expressionPartsTemp = _expression.Split(' ');

                if (expressionPartsTemp.Length < 5)
                {
                    throw new FormatException(string.Format("Error: Expression only has {0} parts.  At least 5 part are required.", expressionPartsTemp.Length));
                }
                else if (expressionPartsTemp.Length == 5)
                {
                    //5 part cron so shift array past seconds element
                    Array.Copy(expressionPartsTemp, 0, parsed, 1, 5);
                }
                else if (expressionPartsTemp.Length == 6)
                {
                    //If last element ends with 4 digits, a year element has been supplied and no seconds element
                    Regex yearRegex = new Regex("\\d{4}$");
                    if (yearRegex.IsMatch(expressionPartsTemp[5]))
                    {
                        Array.Copy(expressionPartsTemp, 0, parsed, 1, 6);
                    }
                    else
                    {
                        Array.Copy(expressionPartsTemp, 0, parsed, 0, 6);
                    }
                }
                else if (expressionPartsTemp.Length == 7)
                {
                    parsed = expressionPartsTemp;
                }
                else
                {
                    throw new FormatException(string.Format("Error: Expression has too many parts ({0}).  Expression must not have more than 7 parts.", expressionPartsTemp.Length));
                }
            }

            NormalizeExpression(parsed);

            return parsed;
        }

        private void NormalizeExpression(string[] expressionParts)
        {
            //convert ? to * only for DOM and DOW
            //expressionParts[3] = expressionParts[3].Replace("?", "*");
            //expressionParts[5] = expressionParts[5].Replace("?", "*");

            //convert 0/, 1/ to */
            //expressionParts[0] = expressionParts[0].Replace("0/", "*/"); //seconds
            //expressionParts[1] = expressionParts[1].Replace("0/", "*/"); //minutes
            //expressionParts[2] = expressionParts[2].Replace("0/", "*/"); //hours
            //expressionParts[3] = expressionParts[3].Replace("1/", "*/"); //DOM
            //expressionParts[4] = expressionParts[4].Replace("1/", "*/"); //Month
            //expressionParts[5] = expressionParts[5].Replace("1/", "*/"); //DOW

            //convert */1 to *
            //int len = expressionParts.Length;
            //for (int i = 0; i < len; i++)
            //{
            //    if (expressionParts[i] == "*/1")
            //    {
            //        expressionParts[i] = "*";
            //    }
            //}


            if (expressionParts[5] == "L")
                expressionParts[5] = "6";
            //convert SUN-SAT format to 0-6 format
            for (int i = 0; i <= 6; i++)
            {
                if (!_options.DayOfWeekStartIndexZero)
                {
                    expressionParts[5] = expressionParts[5].Replace((i + 1).ToString(), i.ToString());
                }

                DayOfWeek currentDay = (DayOfWeek)i;
                string currentDayOfWeekDescription = currentDay.ToString().Substring(0, 3).ToUpper();
                expressionParts[5] = expressionParts[5].Replace(currentDayOfWeekDescription, i.ToString());
            }

            //convert  JAN-DEC format to 1-12 format
            for (int i = 1; i <= 12; i++)
            {
                DateTime currentMonth = new DateTime(DateTime.Now.Year, i, 1);
                string currentMonthDescription = currentMonth.ToString("MMM", new CultureInfo("en-US")).ToUpper();
                expressionParts[4] = expressionParts[4].Replace(currentMonthDescription, i.ToString());
            }

            //convert 0 second to (empty)
            if (expressionParts[0] == "0")
            {
                expressionParts[0] = string.Empty;
            }
        }
    }
}
